<template>
	<view class="">
		<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="1">
		</u-upload>
		<button @click="submit">确认修改</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				fileList1: [],
				imgUrl:null
			}
		},
		methods: {
			//根据用户名查询用户信息
			async getUserByid() {
				
				const userName = JSON.parse(localStorage.getItem("user")).userName
				console.log(userName)
				const res = await this.$api.getUserDetail({
					userName
				})
				console.log(res)
				if (res.code == 200) {
					localStorage.removeItem('user')
					localStorage.setItem('user', JSON.stringify(res.data.records[0]))
				}
				// console.log(res.data.records[0])
			},
			// 确定保存
			submit(){
				this.userEdit()
			},
			//修改头像
			userEdit:async function(){
				let id = JSON.parse(localStorage.getItem('user')).id
				console.log(id)
				const res = await this.$api.userEdit({
					id,
					avatar:this.imgUrl
				})
				if(res.code==200){
					// this.gs
					this.$tool.header()
					setTimeout(function(){
						uni.navigateBack({
								delta:1,//返回层数，2则上上页
							})
					},500)
					this.getUserByid()
				}else{
					alert('图片上传失败')
				}
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: '/api/user/image', // 接口地址
						filePath: url,
						name: 'file',
						formData: {
							
						},
						success: (res) => {
							console.log(JSON.parse(res.data).msg)
							this.imgUrl=JSON.parse(res.data).msg
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},

		}
	}
</script>

<style scoped>
	.u-upload {
		text-align: center;
	}

	.u-upload__wrap {
		margin: 100px;
	}
</style>
